dojo.require("esri.map");
dojo.require("esri.toolbars.draw");
dojo.require("dijit.dijit"); // optimize: load dijit layer
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.layers.agstiled");
dojo.require("esri.undoManager");
dojo.provide("myModules.customoperation");
var mymap,toolbar;

//初始化地图
function init(){
    // undoManager = new esri.UndoManager();
    mymap = new esri.Map("map");
    //加载天地图
    dojo.declare("TianDiTiledMapServiceLayer", esri.layers.TiledMapServiceLayer, {
        constructor: function() {
            this.spatialReference = new esri.SpatialReference({ wkid:4326 });
            this.initialExtent = (this.fullExtent =
                new esri.geometry.Extent(-180.0, -90.0, 180.0, 90.0, this.spatialReference));
            this.tileInfo = new esri.layers.TileInfo({
                "rows" : 256,
                "cols" : 256,
                "compressionQuality" : 0,
                "origin" : { "x" : -180,"y" : 90},
                "spatialReference" : {"wkid" : 4326},
                "lods" : [
                    {"level" : 0, "resolution" : 0.703125, "scale" : 295497593.05875},
                    {"level" : 1, "resolution" : 0.3515625, "scale" : 147748796.529375},
                    {"level" : 2, "resolution" : 0.17578125, "scale" : 73874398.264688},
                    {"level" : 3, "resolution" : 0.087890625, "scale" : 36937199.132344},
                    {"level" : 4, "resolution" : 0.0439453125, "scale" : 18468599.566172},
                    {"level" : 5, "resolution" : 0.02197265625, "scale" : 9234299.783086},
                    {"level" : 6, "resolution" : 0.010986328125, "scale" : 4617149.891543},
                    {"level" : 7, "resolution" : 0.0054931640625, "scale" : 2308574.945771},
                    {"level" : 8, "resolution" : 0.00274658203125, "scale" : 1154287.472886},
                    {"level" : 9, "resolution" : 0.001373291015625, "scale" : 577143.736443},
                    {"level" : 10, "resolution" : 0.0006866455078125, "scale" : 288571.86822143558},
                    {"level" : 11, "resolution" : 0.00034332275390625, "scale" : 144285.93411071779},
                    {"level" : 12, "resolution" : 0.000171661376953125, "scale" : 72142.967055358895},
                    {"level" : 13, "resolution" : 8.58306884765625e-005, "scale" : 36071.483527679447},
                    {"level" : 14, "resolution" : 4.291534423828125e-005, "scale" : 18035.741763839724},
                    {"level" : 15, "resolution" : 2.1457672119140625e-005, "scale" : 9017.8708819198619},
                    {"level" : 16, "resolution" : 1.0728836059570313e-005, "scale" : 4508.9354409599309},
                    {"level" : 17, "resolution" : 5.3644180297851563e-006, "scale" : 2254.4677204799655}]
            });
            this.loaded = true;
            this.onLoad(this);
        },
        getTileUrl: function(level, row, col) {
            var levelMap = "";
            if(level<10){
                levelMap = "A0512_EMap";
            }else if(level<12){
                levelMap = "B0627_EMap1112";
            }else if(level<18){
                levelMap = "siwei0608";
            }
            return "http://t1.tianditu.cn/DataServer?T=vec_c&"+levelMap+"&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });
    //文字标注
    dojo.declare("TianDiBiaoZhuMapServiceLayer", TianDiTiledMapServiceLayer, {
        getTileUrl: function(level, row, col) {
            return "http://t1.tianditu.cn/DataServer?T=cva_c&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });
    //影像地图
    // dojo.declare("TianDiYXMapServiceLayer", TianDiTiledMapServiceLayer, {
    //     getTileUrl: function(level, row, col) {//wmts
    //         return "http://t1.tianditu.cn/DataServer?T=img_c&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
    //     }
    // });

    dojo.connect(mymap, 'onLoad', function(theMap) {
        //resize the map when the browser resizes
        dojo.connect(dijit.byId('map'), 'resize', map,map.resize);
        loadXmlHttp('all');
    });

    mymap.addLayer(new TianDiTiledMapServiceLayer());
    // mymap.addLayer(new TianDiYXMapServiceLayer());
    mymap.addLayer(new TianDiBiaoZhuMapServiceLayer());
    reExtent = new esri.geometry.Extent({"xmin":116.754667,"ymin":25.170577,"xmax":119.98104,"ymax":34.219344,"spatialReference":{"wkid":102100}});
    mymap.setExtent(reExtent);

    //加载天地图结束
    $("#search").click(function(){
        ShowStationOnMap();
    })

}

function identifyFeatures(evt){
    var extentGeom = pointToExtent(mymap,evt.mapPoint,10);
}
function pointToExtent(map, point, toleranceInPixel) {
    //calculate map coords represented per pixel
    var pixelWidth = map.extent.getWidth() / map.width;
    //calculate map coords for tolerance in pixel
    var toleraceInMapCoords = toleranceInPixel * pixelWidth;
    //calculate & return computed extent
    return new esri.geometry.Extent( point.x - toleraceInMapCoords,
        point.y - toleraceInMapCoords,
        point.x + toleraceInMapCoords,
        point.y + toleraceInMapCoords,
        map.spatialReference );
}
function createToolbar(themap) {
    //resize the map when the browser resizes
    dojo.connect(dijit.byId('map'), 'resize',mymap.resize);
    toolbar = new esri.toolbars.Draw(mymap);
    dojo.connect(toolbar, "onDrawEnd", addToMap);
}

function addToMap(geometry) {
    toolbar.deactivate();
    mymap.showZoomSlider();
    console.log(geometry);
    switch (geometry.type) {
        case "point":
            var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 1), new dojo.Color([0,255,0,0.25]));

            break;
        case "polyline":
            var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,186,207]), 3);
            break;
        case "polygon":
            var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([5,184,250]), 2), new dojo.Color([5,184,250,0.25]));
            break;
        case "multipoint":
            var url='';
            url=dojo.byId("sensor").value;
            console.log(url);
            var symbol=new esri.symbol.PictureMarkerSymbol(url, 24, 24);
            console.log(symbol);
            break;
    }
    var graphic = new esri.Graphic(geometry, symbol);
    mymap.graphics.add(graphic);
}

function ShowStationOnMap(){
    var metal = $("#metal_type").find("option:selected").attr("value");
    loadXmlHttp(metal)
}
function loadXmlHttp(metal){
    var xmlhttp,tr;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4&&xmlhttp.status==200){
            var stations = JSON.parse(xmlhttp.responseText);
            mymap.graphics.clear();
            mymap.infoWindow.hide();
            for (var s = 0; s < stations.length; s++) {
                tr += '<tr onclick="showInfo(this,\''+stations[s].accident+'\',\''+stations[s].metal_kind+'\',\''+stations[s].occupation_standard+'\',\''+stations[s].viticm_kind_name+'\',\''+stations[s].accident_place+'\',\''+stations[s].accident_place+'\')" id="' +stations[s].accident+'" data-x="'+stations[s].longitude+'" data-y="'+stations[s].latitude+'">'+
                    '<td><input type="checkbox"  name="list" value="'+stations[s].id+'"></td>'+
                    '<td>'+stations[s].accident+'</td>'+
                    '<td>'+stations[s].metal_kind_en+'</td>'+
                    '<td>'+stations[s].occupation_standard_en+'</td>'+
                    '<td>'+stations[s].viticm_kind_name+'</td>'+
                    '<td>'+stations[s].viticm_kind_count+'</td>'+
                    '<td><a href="/metal_modify/'+stations[s].id+'/">修改</a><a href="/metal_delete/'+stations[s].id+'/">删除</a><a href="/metal_detail/'+stations[s].id+'/">详情</a></td>'+
                    '</tr>'
                $("#data_table tbody").empty().append(tr);
                stations[s].imageUrl = "/static/img/mark/"+stations[s].metal_kind+"Pin1LargeB.png";
//                var symbol = new esri.symbol.PictureMarkerSymbol(stations[s].imageUrl, 32, 32);
                var symbol =  new esri.symbol.PictureMarkerSymbol({
                    "url":stations[s].imageUrl,
                    "height":32,
                    "width":32,
                    "id":"rrrrrrrrrrrrrrrrttt"
                });
//                console.log(symbol)
                var pt = new esri.geometry.Point(stations[s].longitude, stations[s].latitude, mymap.spatialReference);
                var attr = { "accident": stations[s].accident, "metal_kind": stations[s].metal_kind, "occupation_standard": stations[s].occupation_standard, "viticm_kind_name": stations[s].viticm_kind_name,"accident_place": stations[s].accident_place,"time":stations[s].time };
                var infoTemplate = new esri.InfoTemplate("事故：${accident}", "<p>重金属类型: ${metal_kind}</p><p>行业类型: ${occupation_standard}</p><p>受体类型: ${viticm_kind_name}</p><p>发生时间: ${time}</p><p>事故地点:${accident_place}</p>");
                var graphic = new esri.Graphic(pt, symbol, attr, infoTemplate);
                graphic.imageId= stations[s].id;
                mymap.graphics.add(graphic);
            }
//            $('tr').click(function(){
//                var  longitude= $(this).attr('data-x');
//                var  latitude= $(this).attr('data-y');
//                var pt = new esri.geometry.Point(longitude,latitude, mymap.spatialReference);
//                mymap.infoWindow.show(pt);
//                console.log(mymap.infoWindow.title);
//                mymap.infoWindow.setTitle('fghfdkj');
//                mymap.infoWindow.setContent('fghfdkj');
//
//            })

        }

    }
    xmlhttp.open("GET","/filter/"+metal+"/",true);
    xmlhttp.send();
}
function showInfo(obj,a,b,c,d,e,f){
    var  longitude= $(obj).attr('data-x');
    var  latitude= $(obj).attr('data-y');
    var pt = new esri.geometry.Point(longitude,latitude, mymap.spatialReference);
    mymap.infoWindow.show(pt);
    mymap.infoWindow.setTitle(a);
    mymap.infoWindow.setContent("<p>重金属类型: "+b+"</p><p>行业类型: "+c+"</p><p>受体类型: "+d+"</p><p>发生时间: "+e+"</p><p>事故地点:"+f+"</p>");
}
dojo.addOnLoad(init);
